<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	public $userType = 'Front';
    /**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		if($this->userType=='Front'){//只是前台登录
            //检查登录信息是否存在于数据库中
            $record = User::model()->findByAttributes(array('username'=>$this->username));
            if($record === null){
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            }elseif($record->password !== $this->password){//在这里比较数据中的密码与登录信息中的密码
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            }else{
                $this->setState('userId', $record->userId);
                $this->setState('name', $record->firstName.' '.$record->lastName);
                $this->errorCode = self::ERROR_NONE;
            }
            return !$this->errorCode;
        }

        if($this->userType = 'Back'){//只是后台管理登录
            //检查登录信息是否存在于数据库中
            $record = Admin::model()->findByAttributes(array('email'=>$this->username));//这里用数据库中的邮箱作为用户名
            if($record === null){
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            }else if($record->password !== base64_encode($this->password)){
                //获取base64_encode加密的密码并于数据库中的密码比较
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            }else{
                $this->setState('isAdmin', 1);
                $this->setState('userId', $record->userId);
                $this->setState('name', $record->name);
                $this->errorCode = self::ERROR_NONE;
            }
            return !$this->errorCode;
        }

        /*
        $users=array(
			// username => password
			'demo'=>'demo',
			'admin'=>'admin',
		);
		if(!isset($users[$this->username]))
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		else if($users[$this->username]!==$this->password)
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
			$this->errorCode=self::ERROR_NONE;
		return !$this->errorCode;
        */
        /*
         Action 中的代码:
         所有设置都已经完毕，接下来就是在控制器中使用LoginForm对象.

         路径: Controllers/Front/SiteController.php

         $model=new LoginForm('Front'); // 使用‘User’模型的前台登录表单路径: Controllers/Back/SiteController.php

         $model=new LoginForm('Back'); // 使用 ’AdminUser‘ 模型的后台登录表单
         */
	}
}